<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card class="box-card">
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="rolesList">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['btop', idx1 === scope.row.children.length -1 ? 'b-bottom': '', 'vmiddle']" v-for="(item1, idx1) in scope.row.children" :key="item1.id">
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
                </el-col>
              <el-col :span="19">
                <!-- 渲染二级权限 -->
                <el-row :class="[idx2 === item1.children.length -1 ? '':'b-bottom', 'vmiddle']" v-for="(item2, idx2) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag closable type="success" @close="removeRightById(scope.row, item2.id)">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 渲染三级权限 -->
                  <el-col :span="18">
                    <el-tag closable v-for="(item3) in item2.children" :key="item3.id" type="warning" @close="removeRightById(scope.row, item3.id)">{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" icon="el-icon-edit">编辑</el-button>
            <el-button type="danger" size="mini" icon="el-icon-delete">删除</el-button>
            <el-button type="warning" size="mini" icon="el-icon-setting" @click="showAlloatRightDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightsDialogVisible"
      width="50%" @close="setRightsDialogClosed">
      <el-tree :data="rightsList" :props="treeProps" show-checkbox default-expand-all node-key="id" :default-checked-keys="defKeys" ref="treeRef"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 角色列表数据
      rolesList: [],
      // 控制分配权限对话框显示与隐藏
      setRightsDialogVisible: false,
      // 权限列表数据
      rightsList: [],
      // 树形控件绑定数据对象
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      // 存储默认选中的id值
      defKeys: [],
      roleId: ''
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.rolesList = res.data
      console.log(this.rolesList)
    },
    // 根据权限ID删除对应权限
    async removeRightById (role, rightId) {
      // 弹出框提示用户是否删除
      const confirmRes = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmRes !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      // 删除指定角色的权限
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败！！！')
      }
      // this.getRolesList()
      role.children = res.data
    },
    // 分配权限事件处理函数
    async showAlloatRightDialog (role) {
      this.roleId = role.id
      console.log(role)
      const { data: res } = await this.$http.get('rights/tree')
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限数据失败！！！')
      }
      this.rightsList = res.data
      // 获取当前角色下面所有的三级权限
      this.getLeafKeys(role, this.defKeys)
      this.setRightsDialogVisible = true
    },
    // 获取角色下对应的所有三级权限
    getLeafKeys (node, arr) {
      // 当前节点不包含children属性 则是三级权限
      if (!node.children) {
        return arr.push(node.id)
      }

      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    // 监听分配权限对话框的关闭事件
    setRightsDialogClosed () {
      this.defKeys = ''
    },
    // 点击为当前角色分配权限
    async allotRights () {
      // roles/roleId/rights '106,209'
      const idStr = [...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()].join(',')
      console.log(idStr)
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败')
      }
      this.$message.success('分配权限成功')
      // 刷新角色列表
      this.getRolesList()
      // 关闭分配权限对话框
      this.setRightsDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
  .el-tag{
    margin: 8px;
  }
  .btop{
    border-top: 1px solid #eee;
  }
  .b-bottom{
    border-bottom: 1px solid #eee;
  }
  .vmiddle{
    display: flex;
    align-items: center;
  }
</style>
